<template>
  <div>
    <el-steps direction="vertical" :active="curStep - 1" finish-status="success">
      <el-step title="填写基本信息" @click="curStep = 1"></el-step>
      <el-step title="添加限制条件" @click="curStep = 2"></el-step>
      <el-step title="自定义表单" @click="curStep = 3"></el-step>
    </el-steps>

    <!--    基本信息-->
    <transition name="el-zoom-in-center">
      <el-card v-show="curStep === 1">
        <el-breadcrumb separator-class="el-icon-arrow-right" style="height: 45px">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>创建活动</el-breadcrumb-item>
          <el-breadcrumb-item>活动基本信息</el-breadcrumb-item>
        </el-breadcrumb>


        <el-form :model="activityForm" :rules="rules" ref="activityForm" label-width="100px" class="demo-ruleForm">
          <!--        活动主题填写-->
          <el-form-item label="活动主题" prop="title" style="width: 500px">
            <el-input v-model="activityForm.title"></el-input>
          </el-form-item>

          <!--        活动时间选择-->
          <el-form-item
              label="活动时间"
              prop="activityTime">
            <div class="block">
              <el-date-picker
                  v-model="activityForm.activityTime"
                  type="datetimerange"
                  :picker-options="pickerOptions1"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  align="right">
              </el-date-picker>
            </div>
          </el-form-item>

          <!--        报名时间选择-->
          <el-form-item
              label="报名时间"
              prop="applyTime">
            <div class="block">
              <el-date-picker
                  v-model="activityForm.applyTime"
                  type="datetimerange"
                  :picker-options="pickerOptions2"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  align="right">
              </el-date-picker>
            </div>
          </el-form-item>

          <!--        活动附件上传-->
          <el-form-item label="上传附件" enctype="multipart/form-data" prop="formData">
            <el-button
                size="mini"
                type="primary"
                class="button"
                @click="goFile">
              <i class="el-icon-upload2"></i> 上传
            </el-button>

            <input
                type="file"
                style="display: none;"
                id="file"
                ref="files"
                accept="application/zip"
                @click="e => {e.target.value = '';}"
                @change="showChange($event)"
            />

            <input
                v-model="this.fileName"
                placeholder="文件大小不能超过10M  有且上传一个文件  仅支持zip"
                disabled="true"
                style="outline: none; border: 0; width: 500px; margin-left: 20px"
            />
          </el-form-item>


          <!--        活动详情填写-->
          <el-form-item
              label="活动详情"
              prop="activityContent">
            <quillEditor
                ref="getContentData"
                v-model="activityForm.activityContent"/>
          </el-form-item>

          <el-form-item class="formButton">
            <el-button type="primary" size="small" @click="goSecondCard('activityForm')">下一步</el-button>
            <!--            <el-button @click="$router.push('/')"-->
            <!--                       type="danger"-->
            <!--                       plain-->
            <!--                       size="small">-->
            <!--              取消-->
            <!--            </el-button>-->
          </el-form-item>

        </el-form>
      </el-card>
    </transition>

    <!--    限制条件-->
    <transition name="el-zoom-in-center">
      <el-card v-show="curStep === 2">
        <el-breadcrumb separator-class="el-icon-arrow-right" style="height: 45px">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>创建活动</el-breadcrumb-item>
          <el-breadcrumb-item>
            <span @click="curStep=1" class="breadHover">活动基本信息</span></el-breadcrumb-item>
          <el-breadcrumb-item>报名限制条件</el-breadcrumb-item>
        </el-breadcrumb>

        <el-form :model="activityForm.restriction" :rules="rules" ref="restriction">
          <el-form-item label="地域选择" prop="area">
            <el-cascader
                :options="restriction.area"
                :props="{ multiple: true,
                          checkStrictly: true,
                          value: 'regionCode',
                          label: 'regionName',
                          emitPath: true}"
                v-model="activityForm.restriction.area"
                placeholder="无限制"
                clearable></el-cascader>
          </el-form-item>

          <el-form-item label="学院选择" prop="college">
            <!--            <el-cascader-->
            <!--                :options="restriction.college"-->
            <!--                :props="{ multiple: true,-->
            <!--                          checkStrictly: true,-->
            <!--                          value: 'id',-->
            <!--                          label: 'name',-->
            <!--                          children: 'majorList',-->
            <!--                          emitPath: true}"-->
            <!--                v-model="activityForm.restriction.college"-->
            <!--                placeholder="无限制"-->
            <!--                clearable></el-cascader>-->
            <el-select v-model="activityForm.restriction.college" multiple placeholder="请选择">
              <el-option
                  v-for="item in restriction.college"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="年级选择" prop="grade">
            <el-select v-model="activityForm.restriction.grade" clearable multiple placeholder="无限制">
              <el-option
                  v-for="item in restriction.grade"
                  :key="item"
                  :label="item"
                  :value="item">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="性别选择" prop="sex">
            <el-select v-model="activityForm.restriction.sex" clearable placeholder="无限制">
              <el-option
                  v-for="item in restriction.sex"
                  :key="item.sex"
                  :label="item.sex"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="每队最多人数" prop="teamSize" style="width: 300px">
            <el-input v-model="activityForm.restriction.teamSize"
                      placeholder="无限制"
                      oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value<=0)value=null;if(value>=99)value=99"
                      type="number"></el-input>
          </el-form-item>

          <el-form-item label="限制队伍数量" prop="teamNumber" style="width: 300px">
            <el-input v-model="activityForm.restriction.teamNumber"
                      placeholder="无限制"
                      oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value<=0)value=null;if(value>=999)value=999"
                      type="number"></el-input>
          </el-form-item>


          <el-form-item class="formButton">
            <el-button @click="curStep = 1"
                       type="info"
                       plain
                       size="small">
              上一步
            </el-button>
            <el-button type="primary" size="small" @click="goThirdCard('restriction')">下一步</el-button>
          </el-form-item>
        </el-form>

      </el-card>
    </transition>

    <!--    自定义问题-->
    <transition name="el-zoom-in-center">
      <el-card v-show="curStep === 3">
        <el-breadcrumb separator-class="el-icon-arrow-right" style="height: 45px">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>创建活动</el-breadcrumb-item>
          <el-breadcrumb-item>
            <span @click="curStep=1" class="breadHover">活动基本信息</span></el-breadcrumb-item>
          <el-breadcrumb-item>
            <span @click="curStep=2" class="breadHover">报名限制条件</span></el-breadcrumb-item>
          <el-breadcrumb-item>自定义表单</el-breadcrumb-item>
        </el-breadcrumb>

        <el-form ref="questions"
                 :model="activityForm.questions"
                 label-position="right"
                 label-width="100px">
          <vuedraggable v-model="activityForm.questions"
                        class="wrapper"
                        @end="end">
            <el-collapse :v-model="activeIndex">
              <el-collapse-item v-for="(item, index) in activityForm.questions" :key="index" :name="index + 1">
                <template slot="title">
                  第{{ index + 1 }}题：{{ item.questionName }}
                </template>
                <!-- 问题 -->
                <el-form-item
                    :prop="`${index}.type`"
                    :label="`问题${index + 1}类型`"
                    :rules="{ required: true, message: '请选择问题类型', trigger: 'change' }">
                  <el-radio-group v-model="item.type">
                    <el-radio :label="1">填空题</el-radio>
                    <el-radio :label="2">单选题</el-radio>
                    <el-radio :label="3">多选题</el-radio>
                    <!--                    <el-radio :label="4">判断题</el-radio>-->
                  </el-radio-group>
                </el-form-item>
                <!--问题-->
                <el-form-item
                    :prop="`${index}.questionName`"
                    label="问题"
                    :rules="{ required: true, message: '请填写问题', trigger: 'change' }">
                  <el-input v-model.trim="item.questionName"
                            style="width:450px"
                            clearable
                            placeholder="请填写问题"/>
                </el-form-item>
                <el-form-item
                    :prop="`${index}.hint`"
                    label="填空题提示"
                    v-show="item.type === 1">
                  <el-input v-model.trim="item.hint"
                            style="width:450px"
                            clearable
                            placeholder="请填写填空题的填写提示"/>
                </el-form-item>
                <!-- 选项 -->
                <el-form-item
                    v-show="item.type !== 1 && item.type !== 4"
                    v-for="(opt, idx) in item.answers"
                    :key="idx"
                    :label="`选项${idx + 1}`"
                    :prop="`${index}.answers.${idx}.value`"
                    :rules="[
                        { required: true, message: '请输入选项', trigger: 'blur' },
                      ]">
                  <el-input v-model.trim="opt.value"
                            style="width:450px"
                            clearable
                            placeholder="请输入选项"/>
                  <el-button v-if="idx + 1 > 2"
                             style="margin-left: 20px"
                             type="danger"
                             size="small"
                             @click.prevent="removeDomain(index,idx)">
                    删除
                  </el-button>
                </el-form-item>
                <el-form-item>
                  <el-button v-show="item.type !== 1 && item.type !== 4"
                             @click="addDomain(index)"
                             type="primary"
                             size="small">
                    新增选项
                  </el-button>
                  <el-button @click="removeQuestion(index)"
                             type="danger"
                             size="small">
                    删除题目
                  </el-button>
                </el-form-item>
              </el-collapse-item>
            </el-collapse>

          </vuedraggable>
          <el-form-item>
            <el-button @click="addQuestion"
                       type="primary"
                       size="small">
              新增题目
            </el-button>
          </el-form-item>
          <el-form-item class="formButton">
            <el-button @click="curStep = 2"
                       type="info"
                       plain
                       size="small">
              上一步
            </el-button>
            <el-button style="margin-top: 10px"
                       @click="addSubmit()"
                       type="success"
                       size="small">
              创建活动
            </el-button>

          </el-form-item>
        </el-form>

      </el-card>
    </transition>
  </div>
</template>

<script>
import quillEditor from '../../components/quillEdior'
import vuedraggable from 'vuedraggable'
import RequestUtil from "../../../utils/RequestUtil";
import ParamsUtil from "../../../utils/ParamsUtil"
import areas from "../../../plugins/region"
import loading from "../../../loading";

let date = new Date()
let nowYear = date.getFullYear()

export default {
  name: "CreateActivity",
  components: {
    quillEditor,
    vuedraggable
  },
  data() {
    return {
      rules: {
        title: [
          {required: true, message: '请输入活动名称', trigger: 'blur'},
          {min: 7, max: 20, message: '长度在 7 到 20 个字符', trigger: 'blur'}
        ],
        activityTime: [
          {required: true, message: '请选择活动时间', trigger: 'change'}
        ],
        applyTime: [
          {required: true, message: '请选择报名时间', trigger: 'change'}
        ],
        activityContent: [
          {required: true, message: '请选择报名时间', trigger: 'change'}
        ],
      },
      activityId: '',
      activeIndex: [1],
      curStep: 1,
      fileName: '文件大小不能超过10M  有且上传一个文件  仅支持zip',
      file: '',
      activityForm: {
        title: '',
        activityTime: [],
        applyTime: [],
        activityContent: '',
        questions: [],
        restriction: {
          //学院专业限制
          college: [],
          //年级限制
          grade: [],
          //地域限制
          area: [],
          //性别限制
          sex: '',
          //小队人数限制
          teamSize: '',
          //小队数量限制
          teamNumber: ''
        },
      },
      activityRestriction: {},
      restriction: {
        area: areas,
        college: [],
        grade: [
          nowYear,
          nowYear - 1,
          nowYear - 2,
          nowYear - 3,
          nowYear - 4,
        ],
        sex: [{
          id: '1',
          sex: '男'
        }, {
          id: '2',
          sex: '女'
        },],
      },
      cover: '',
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
        },
        shortcuts: [{
          text: '未来一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '未来一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '未来三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
        },
        shortcuts: [{
          text: '未来一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '未来一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '未来三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    }
  },
  created() {
    // this.getRestriction()
    RequestUtil.sendCacheableRequest("collegeList", '/auth/getCollegeList').then((collegeList) => {
      this.restriction.college = collegeList
    })

    this.activityId = this.$route.params.activityId
  },
  methods: {
    //获取限制数据
    // getRestriction() {
    //   this.$axios.get(`${this.HOST}activity/getCollegeAndMajorInfo`).then(res => {
    //     const info = res.data
    //     CacheUtil.setRestriction(info)
    //     this.restriction.college = info.data
    //   })
    // },
    //跳转到其他页面
    goSecondCard(formName) {
      if (this.activityForm.activityTime[0] < this.activityForm.applyTime[0]) {
        this.$message({
          message: '报名开始时间不能晚于活动开始时间',
          type: 'error',
          offset: 90,
          duration: 1000
        })
        return false
      }

      if (this.activityForm.activityTime[1] < this.activityForm.applyTime[1]) {
        this.$message({
          message: '报名结束时间不能晚于活动结束时间',
          type: 'error',
          offset: 90,
          duration: 1000
        })
        return false
      }

      //获取富文本内容
      this.activityForm.activityContent = this.$refs.getContentData.content
      //给问卷card换样式
      this.activityForm.cover = this.$refs.getContentData.pictureUri

      const updateArr = ['title', 'activityTime', 'applyTime']
      // console.log("fN", formName, this.$refs[formName])
      let _this = this;
      let allowToGo = true;
      this.$refs[formName].validateField(updateArr, res => {
        // console.log(res)
        if (res !== '') allowToGo = false;
      })
      if (allowToGo) {
        this.curStep = 2;
      }
      // console.log("end")
    },
    //跳转到其他页面
    goThirdCard(formName) {
      this.curStep = 3;
    },
    //选择上传的文件
    goFile() {
      this.$refs.files.click();
    },
    //获取上传文件
    showChange(e) {
      let file = e.target.files[0];
      this.fileName = file.name;
      this.file = file;
    },
    removeDomain(index, idx) { // 删除选项
      this.activityForm.questions[index].answers.splice(idx, 1)
    },
    removeQuestion(index) { // 删除题目
      this.activityForm.questions.splice(index, 1)
    },
    addDomain(index) { // 新增选项
      this.activityForm.questions[index].answers.push({value: ''})
    },
    addQuestion() { // 新增题目
      this.activityForm.questions.push({type: 1, questionName: '', answers: [{value: ''}, {value: ''}]})
    },
    end() {
      this.$refs.activityForm.clearValidate()
    },
    addSubmit() {
      const _loading = loading(`活动创建中，请稍等...`);
      const config = {
        onUploadProgress: (progressEvent) => {
          this.progressPercent = Number(
              ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
          );
          _loading.setText(
              "活动创建中，进度：" + this.progressPercent + "%"
          ); //更新dialog进度，优化体验
          // console.log(this.progressPercent);
        },
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };

      this.activityRestriction = this.activityForm.restriction

      this.activityRestriction.college = ParamsUtil.ToOneDimensionalArray(this.activityForm.restriction.college)
      this.activityRestriction.area = ParamsUtil.ToOneDimensionalArray(this.activityForm.restriction.college)


      let params = {
        content: this.activityForm.activityContent,
        title: this.activityForm.title,
        applyTime: this.activityForm.applyTime,
        activityTime: this.activityForm.activityTime,
      }

      // 发送请求
      let requestData = ParamsUtil.convertToFormData(params, false);
      requestData.append("file", this.file);
      requestData.append("questions", JSON.stringify(ParamsUtil.toArray(this.activityForm.questions)))
      requestData.append("activityRestriction", JSON.stringify(this.activityRestriction))
      try {
        this.$axios.post(`${this.HOST}activity/createCompleteActivity`,
            requestData, config).then(res => {
          if (res.data.code === 200) {
            this.$message({
              message: res.data.message,
              type: 'success',
              offset: 90,
              duration: 1000
            })
            this.$router.go(0)
            this.$router.push('/activities')
          }
        }).then(() => {
          _loading.close()
        })
      } finally {
        console.log("")
      }
    }
  }
}
</script>

<style lang="less" scoped>

.fileName {
  width: 400px;
  height: 40px;
  line-height: 40px;
  border: 1px solid #cccccc;
  padding-left: 14px;
  box-sizing: border-box;
  margin-left: 18px;
}

.formButton {
  width: 95%;
  display: flex;
  justify-content: flex-end;
}

.breadHover:hover {
  cursor: pointer;
  text-decoration: underline;
}

.el-steps {
  position: fixed;
  left: 20px;
  top: 50px;
  height: 300px;
  width: 8%;

  /deep/ .el-step__title {
    font-weight: normal;;
    font-size: 14px;
  }
}

.el-card {
  position: absolute;
  width: 100%;
}

</style>
